import { _decorator, Button, Component, EditBox, Label, Node, Sprite, Toggle } from 'cc';
import { isPositiveInteger } from '../utils/regex_func';
import { isAllowNextStep, LocalStorageKeysEnum, NodeName } from '../utils/common';
import { LpApi } from '../apis/live-platform/LpApi';
const { ccclass, property } = _decorator;

@ccclass('VerifyRealPerson')
export class VerifyRealPerson extends Component {
    private verify_rule_button: Node = null;
    private statistics_player_button: Node = null;
    private display_player_button: Node = null;

    protected onLoad(): void {
        // ----------------------找到对应的节点-------------------
        this.verify_rule_button = this.node.getChildByName(NodeName.LiveRoomScene.Node.OperatorBarNode).getChildByName(NodeName.LiveRoomScene.Button.VerifyRuleButton);
        this.statistics_player_button = this.node.getChildByName(NodeName.LiveRoomScene.Node.OperatorBarNode).getChildByName(NodeName.LiveRoomScene.Button.StatisticsPlayerButton);
        this.display_player_button = this.node.getChildByName(NodeName.LiveRoomScene.Node.OperatorBarNode).getChildByName(NodeName.LiveRoomScene.Button.DisplayPlayerButton);

        // ----------------------给节点绑定函数--------------------
        this.verify_rule_button.on(Button.EventType.CLICK, this.onVerifyRuleButtonClick, this);
        this.statistics_player_button.on(Button.EventType.CLICK, this.onStatisticsPlayerButtonClick, this);
        this.display_player_button.on(Button.EventType.CLICK, this.onDisplayPlayerButtonClick, this);
        
        this.node.getComponentsInChildren(EditBox).forEach((edit_box) => {
            edit_box.node.on(EditBox.EventType.TEXT_CHANGED, this.checkEditboxValueFormat, edit_box);
        })

        this.node.getComponentsInChildren(Toggle).forEach((toggle) => {
            toggle.node.on(Toggle.EventType.CLICK, this.onToggleClick, toggle);
        })
    }

    protected onDestroy(): void {
        if(this.verify_rule_button !== null && this.verify_rule_button !== undefined && this.verify_rule_button.name.length) {
            this.verify_rule_button.off(Button.EventType.CLICK, this.onVerifyRuleButtonClick, this);
        }
        if(this.statistics_player_button !== null && this.statistics_player_button !== undefined && this.statistics_player_button.name.length){
            this.statistics_player_button.off(Button.EventType.CLICK, this.onStatisticsPlayerButtonClick, this);
        }
        if(this.display_player_button !== null && this.display_player_button !== undefined && this.display_player_button.name.length){
            this.display_player_button.off(Button.EventType.CLICK, this.onDisplayPlayerButtonClick, this);
        }
        if(this.node !== null && this.node !== undefined && this.node.name.length){
            this.node.getComponentsInChildren(EditBox).forEach((edit_box) => {
                if (edit_box !== null && edit_box !== undefined && edit_box.name.length){
                    edit_box.node.off(EditBox.EventType.TEXT_CHANGED, this.checkEditboxValueFormat, edit_box);
                }
            })
        }
        if (this.node !== null && this.node !== undefined && this.node.name.length){
            this.node.getComponentsInChildren(Toggle).forEach((toggle) => {
                if (toggle !== null && toggle !== undefined && toggle.name.length){
                    toggle.node.off(Toggle.EventType.CLICK, this.onToggleClick, toggle);
                }
            })
        }
    }

    static initVerifyRealPerson(verify_real_person_sprite: Node) {
        /**
         * 初始化真人验证信息
        */
        let edit_box_array: EditBox[] = verify_real_person_sprite.getComponentsInChildren(EditBox);
        for (let i=0; i<=edit_box_array.length-1; i++) {
            edit_box_array[i].string = "";
            if (i == edit_box_array.length - 1) {
                edit_box_array[i].node.active = false;
            } else {
                edit_box_array[i].node.active = true
            }
        }

        let toggle_array: Toggle[] = verify_real_person_sprite.getComponentsInChildren(Toggle);
        for (let i=0; i<=toggle_array.length -1; i++) {
            if (i === toggle_array.length-1) {
                toggle_array[i].isChecked = false;
            } else {
                toggle_array[i].isChecked = true;
            }
        }
    }

    checkEditboxValueFormat(event: InputEvent) {
        /**
         * 检测输入框值的格式
         * 1. 需要输入框的值是正整数。
        */
        let node: Node = event['node'];
        if (isPositiveInteger(event['string']) || event['string'].length === 0){
            node.parent.getChildByName(`${node['name'].replace('EditBox', '')}Label`).getComponent(Label).string = "";
        } else {
            if (node['name'].indexOf('Barrage') === -1) {
                node.parent.getChildByName(`${node['name'].replace('EditBox', '')}Label`).getComponent(Label).string = "请输入大于0的整数";
            }
        }
    }

    onToggleClick(event: InputEvent) {
        /**
         * 单选框点击事件：当被点中时，影藏未被点中对应的editbox框
        */
        let node: Node = event['node'];
        for (let edit_box of node.parent.parent.getComponentsInChildren(EditBox)) {
            if (edit_box.node.name.indexOf('SecondsNum') === -1) {
                if (node['name'].indexOf(edit_box.node.name.replace('EditBox', '')) !== -1) {
                    edit_box.node.active = true;
                } else {
                    edit_box.node.active = false;
                }
            }
        }
    }

    onVerifyRuleButtonClick() {
        /**
         * 获取秒数、点赞次数或弹幕内容
        */
        const _Step = "VerifyRule";
        if (isAllowNextStep(localStorage.getItem('GameStep'), _Step)) {
            let form_data: object = {};
            this.node.getComponentsInChildren(Toggle).forEach((toggle) => {
                if (toggle.isChecked) {
                    if (toggle.node.name.indexOf('Likes') !== -1) {
                        form_data['rule'] = 'Likes';     // 点赞
                    } else if (toggle.node.name.indexOf('Barrage') !== -1) {
                        form_data['rule'] = 'Barrage';   // 弹幕
                    }
                }
            })
            this.node.getComponentsInChildren(EditBox).forEach((edit_box) => {
                form_data[edit_box.node.name] = edit_box.string;
            })
            // 通过网络向直播平台发送请求
            LpApi.verifyRealPersonRuleApi(form_data);
            localStorage.setItem('GameStep', _Step);
        } else {
            // throw new Error("请根据按钮顺序逐步操作");
        }
    }

    onStatisticsPlayerButtonClick() {
        const _Step = "StatisticsPlayer";
        if (isAllowNextStep(localStorage.getItem('GameStep'), _Step)) {
            // 在指定时间后，向直播平台发送请求，获取指定时间范围内的弹幕或点赞信息
            let real_person_list = LpApi.verifyRealPersonStatisticsApi();
            localStorage.setItem(`${LocalStorageKeysEnum.VerifyRealPersonJson}`, JSON.stringify(real_person_list === undefined ? {}:real_person_list));
            localStorage.setItem('GameStep', _Step);
        } else {
            // throw new Error("请根据按钮顺序逐步操作");
        }
    }

    onDisplayPlayerButtonClick() {
        const _Step = "DisplayPlayer";
        if (isAllowNextStep(localStorage.getItem('GameStep'), _Step)) {
            let real_person_list = JSON.parse(localStorage.getItem(`${LocalStorageKeysEnum.VerifyRealPersonJson}`));
            // 将统计出的真人名单公布在直播平台的直播间中
            LpApi.verifyRealPersonDisplayApi(real_person_list);
            localStorage.setItem('GameStep', _Step);
        } else {
            // throw new Error("请根据按钮顺序逐步操作");
        }
    }
}


